
#include <Arduino.h>
#include <U8g2lib.h>
#include <Wire.h>
 
#define UP_KEY      5 //gpio12
#define M_KEY       4 //gpio14
#define DOWN_KEY    0 //gpio13
 
//读取键值
#define keyup     digitalRead(UP_KEY)
#define keyenter  digitalRead(M_KEY)
#define keydown   digitalRead(DOWN_KEY)
 
uint8_t func_index=0;
void (*current_operation_index)();
void fun1();
void fun2();
void fun3();
void fun4();
void page_1_to_4();
 
typedef struct
{
	uint8_t current;
	uint8_t up;//向上翻索引号
	uint8_t down;//向下翻索引号
	uint8_t enter;//确认索引号
	void (*current_operation)();
}key_table;
 
key_table table[7]=
{
	{0,3,1,0,(*fun1)},
	{1,0,2,1,(*fun2)},
	{2,1,3,2,(*fun3)},
	{3,2,0,3,(*fun4)},
};
 
U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2( U8G2_R0, /* clock=*/ 13, /* data=*/ 14, /* reset=*/ U8X8_PIN_NONE );
 
void setup(void)
{
  pinMode(UP_KEY, INPUT_PULLUP);
  pinMode(M_KEY, INPUT_PULLUP);
  pinMode(DOWN_KEY, INPUT_PULLUP);
  u8g2.begin();
  u8g2.enableUTF8Print();
  ESP.wdtEnable(5000);//看门狗初始化
}
 
void loop(void)
{
  /*******************find index****************************/
	if((keyup==0)||(keydown==0)||(keyenter==0))
	{
		delay(10);//消抖
		if(keyup==0)
		{
			func_index=table[func_index].up;    //向上翻
			while(!keyup)ESP.wdtFeed();// 喂 狗    
		}
		if(keydown==0)
  	{
    	func_index=table[func_index].down;    //向下翻
    	while(!keydown)ESP.wdtFeed();// 喂 狗    
		}
    if(keyenter==0)                     
		{                
		  func_index=table[func_index].enter;    //确认
		  while(!keyenter)ESP.wdtFeed();// 喂 狗
		}
	}
	current_operation_index=table[func_index].current_operation;
	(*current_operation_index)();//执行当前操作函数
  ESP.wdtFeed();// 喂 狗     
}
 
void fun1(){
  u8g2.clearBuffer();
  page_1_to_4();
  //显示光标
  u8g2.setFont(u8g2_font_open_iconic_all_1x_t);
  u8g2.drawGlyph(5, 16*(1%4==0? 4:1%4)-4,118);
  u8g2.sendBuffer();
}
void fun2(){
  u8g2.clearBuffer();
  page_1_to_4();
  //显示光标
  u8g2.setFont(u8g2_font_open_iconic_all_1x_t);
  u8g2.drawGlyph(5, 16*(2%4==0? 4:2%4)-4,118);
  u8g2.sendBuffer();
}
void fun3(){
  u8g2.clearBuffer();
  page_1_to_4();
  //显示光标
  u8g2.setFont(u8g2_font_open_iconic_all_1x_t);
  u8g2.drawGlyph(5, 16*(3%4==0? 4:3%4)-4,118);
  u8g2.sendBuffer();
}
void fun4(){
  u8g2.clearBuffer();
  page_1_to_4();
  //显示光标
  u8g2.setFont(u8g2_font_open_iconic_all_1x_t);
  u8g2.drawGlyph(5, 16*(4%4==0? 4:4%4)-4,118);
  u8g2.sendBuffer();
}
void page_1_to_4(){
  u8g2.setFont(u8g2_font_wqy14_t_gb2312a);
  u8g2.setCursor(20, 16*1-2);
  u8g2.print(" 1.桌面设置");
  u8g2.setCursor(20, 16*2-2);
  u8g2.print(" 2.屏幕设置");
  u8g2.setCursor(20, 16*3-2);
  u8g2.print(" 3.网络信息");
  u8g2.setCursor(20, 16*4-2);
  u8g2.print(" 4.智能配网");
}